package com.soft.bams.client;

import com.soft.bams.entity.Account;

import javax.swing.*;


public class LoginPanel extends JPanel {
    private ATMClient atmClient;

    private JLabel idLabel = new JLabel("用户账号:");
    private JLabel passwordLabel = new JLabel("用户密码:");

    private JTextField idField = new JTextField();
    private JPasswordField passwordField = new JPasswordField();

    private JButton confirmBtn = new JButton("确认");
    private JButton cancelBtn = new JButton("取消");

    public LoginPanel(ATMClient atmClient) {
        this.atmClient = atmClient;
        setLayout(null);
        initComponents();
    }

    private void initComponents() {
        // 设置组件位置和大小
        idLabel.setBounds(150, 100, 80, 25);
        idField.setBounds(240, 100, 150, 25);

        passwordLabel.setBounds(150, 150, 80, 25);
        passwordField.setBounds(240, 150, 150, 25);

        confirmBtn.setBounds(170, 200, 80, 30);
        cancelBtn.setBounds(270, 200, 80, 30);

        // 添加组件
        add(idLabel);
        add(idField);
        add(passwordLabel);
        add(passwordField);
        add(confirmBtn);
        add(cancelBtn);

        // 事件处理
        confirmBtn.addActionListener(e -> {
            try {
                long id = Long.parseLong(idField.getText());
                String password = new String(passwordField.getPassword());

                Object response = atmClient.sendCommand("login#" + id + "#" + password);

                if (response instanceof Account) {
                    Account account = (Account) response;
                    atmClient.getBusinessPanel().setAccount(account);
                    atmClient.showPanel("Business");
                    idField.setText("");
                    passwordField.setText("");
                } else if (response instanceof String) {
                    JOptionPane.showMessageDialog(this, response, "错误", JOptionPane.ERROR_MESSAGE);
                }
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(this, "登录失败", "错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelBtn.addActionListener(e -> {
            idField.setText("");
            passwordField.setText("");
            atmClient.showPanel("Main");
        });
    }
}
